package d0319;

public class Withdrow {
    volatile boolean hasEggs = false;//提供同步得变量设置
    int balance = 1000;
    Object flag=new Object();
    Thread human = new Thread(() -> {
        while (true) {
            if (hasEggs) {
                System.out.println("余额不足，等待");
                synchronized (flag) {
                    try {
                        flag.wait();//阻塞
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } else {
                balance -= 100;
                System.out.println(Thread.currentThread().getName()+"取走100元,还剩"+balance+"元");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if(balance == 0) {
                    hasEggs = false;
                }
            }
        }
    });
    Thread human1 = new Thread(() -> {
        while (true) {
            if (hasEggs) {
                System.out.println("余额不足，等待");
                synchronized (flag) {
                    try {
                        flag.wait();//阻塞
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } else {
                balance -= 100;
                System.out.println(Thread.currentThread().getName()+"取走100元,还剩"+balance+"元");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if(balance == 0) {
                    hasEggs = false;
                }
            }
        }
    });

    Thread hen = new Thread(() -> {
        while (true) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            hasEggs = false;
            balance += 2000;
            System.out.println(Thread.currentThread().getName()+"存入2000元，还剩"+balance + "元");
            synchronized (flag){
                flag.notifyAll();//唤醒
            }
        }
    });


    public static void main(String[] args) {
        Withdrow eggTest=new Withdrow();
        eggTest.human.setName("A");
        eggTest.human1.setName("B");
        eggTest.hen.setName("C");
        eggTest.human.start();
        eggTest.human1.start();
        eggTest.hen.start();
    }
}